package net.lastcoder.ifserver.server;

import net.lastcoder.ifserver.Globals;
import net.lastcoder.ifserver.module.BaseModule;
import net.lastcoder.ifserver.module.ModuleNames;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
 * auth: WenYF
 * date: 2016/11/23
 */
public class ServerManager extends BaseModule {
    private static final Logger Log = LoggerFactory.getLogger(ServerManager.class);

    private static ServerManager instance = new ServerManager();

    public static ServerManager getInstance() {
        return instance;
    }

    private HashMap<String, ServerSession> terminates;

    private String rootUid;
    private String rootPassword;
    private int counter;
    public ServerManager() {
        super(ModuleNames.ServerManager);
        terminates = new HashMap<>();
        counter = 0;
        rootUid = Globals.getXMLProperty("terminate.root.username", "wyf");
        rootPassword = Globals.getXMLProperty("terminate.root.password", "wyf520");
    }

    public String generateName() {
        return rootUid + "-" + counter++;
    }

    public String generateUid() {
        return rootUid;
    }

    public String getRootPassword() {
        return rootPassword;
    }

    public String getRootUid() {
        return rootUid;
    }

    @Override
    public void init() {
    }

    @Override
    public void reload() {
    }

    @Override
    public void destroy() {
        String shutdown = "ifserver has been shutdown";
        for (ServerSession session : new ArrayList<>(terminates.values())) {
            session.deliverRawData(shutdown.getBytes());
            session.close();
        }
        terminates.clear();
    }

    public void addTerminateSession(ServerSession session) {
        terminates.put(session.getUsername(), session);
    }

    public void removeTerminateSession(ServerSession session) {
        terminates.remove(session.getUsername());
    }

    public int getTerminateCounts() {
        return terminates.size();
    }

    public Collection<ServerSession> getTerminateSessions() {
        return terminates.values();
    }
}
